package ca.ubc.cpsc210.waldo.translink;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import ca.ubc.cpsc210.waldo.model.Bus;
import ca.ubc.cpsc210.waldo.model.BusRoute;
import ca.ubc.cpsc210.waldo.model.BusStop;
import ca.ubc.cpsc210.waldo.util.LatLon;

public class TranslinkServiceFromXMLFile extends TranslinkService {

	@Override
	public void getBusStopsAround(LatLon location, int radius, Reader input) {
		
		try {
			Set<BusStop> stops = new HashSet<BusStop>();
			
			XMLReader reader = XMLReaderFactory.createXMLReader();
			UBCBusStopsParser handler = new UBCBusStopsParser(stops, radius);
			reader.setContentHandler(handler);
			reader.parse(new InputSource(input));
			
			for (BusStop stop : stops) {
				super.addBusStop(stop);
//				System.out.println("Added: " + stop.getNumber() + "-" + stop.getName() + "-" + stop.getRoutes().size());

			}
			
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void getBusEstimtesForStop(BusStop stop, Reader input) {
		
		try {
			List<BusRoute> routes = new ArrayList<BusRoute>();
			
			XMLReader reader = XMLReaderFactory.createXMLReader();
			BusEstimatesParser handler = new BusEstimatesParser(stop, routes);
			reader.setContentHandler(handler);
			reader.parse(new InputSource(input));
						
			for (BusRoute route : routes) {
				for (Bus bus : route.getBuses()) {
					super.lookupRoute(route.getRouteNumber()).addBus(bus);
				}
//				System.out.println("Added: " + route.getRouteNumber() + "-------------------------------" + route.getRouteNumber());
			}
			
			
			
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
